const path = require("path");
const fs = require("fs");
const awaitWriteStream = require("await-stream-ready").write;

const Controller = require("egg").Controller;

class UploadController extends Controller {
  async upload() {
    const ctx = this.ctx;
    const stream = await ctx.getFileStream();
    console.log(stream);
    const filename =
      Date.now() + path.extname(stream.filename).toLocaleLowerCase();
    const target = path.join(
      this.config.uploadDir,
      "app/public/uploads",
      filename
    );
    const writeStream = fs.createWriteStream(target);
    try {
      // 写入文件
      await awaitWriteStream(stream.pipe(writeStream));
      ctx.body = { name: filename };
      ctx.status = 200;
    } catch (err) {
      // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
      await sendToWormhole(stream);
      ctx.body = { msg: "写入图片失败" };
      ctx.status = 400;
      throw err;
    }
  }
}

module.exports = UploadController;
